import {reactive,ref,toRefs} from 'vue'
import {debounce } from 'lodash'
import { ElMessage } from 'element-plus';

export const useTable = (api,searchParam={})=>{
	const state = reactive({
		loading :false,
		tableData:[],
		page:{
			current:1,
			size:10,
			totalCount:1,
			sizeOption:[10,20,30,40,50,100]
		}
	})
	// 获取数据列表信息
	const loadList = async(params={
		current:state.page.current,
		size:state.page.size,
		...searchParam,
	})=>{
		state.loading = true
		const {code,data,msg,count} = await api(params).catch((e)=>e)
		console.log('---------useTable ---------');
		console.log('---------code ---------',code);
		console.log('---------data ---------',data);
		console.log('---------code ---------',code);
		state.loading = false
		if(code === 200){
			 state.tableData = data.page.records;
			 state.page.totalCount = data.page.total;
		}else if(msg){
			  ElMessage.error(msg);
		}
	}
	
	// 分页切换方法
	const handleSizeChange = (val)=>{
		state.page.size = val
		loadList()
	}
	// 表格数据搜索
	const searchData = debounce((loadList)=>{
		loadList()
	},500)
	
	//返回相关的变量
	// 返回相关变量与方法
	  return {
	    ...toRefs(state),
	    loadList,
	    handleSizeChange,
	    searchData,
	  }
}